package com.stylefeng.guns.modular.huamao.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageHelper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.util.*;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 用户账户控制器
 *
 * @author 刘端
 * @Date 2018-05-08 11:06:33
 */
@CrossOrigin
@SuppressWarnings("all")
@RestController
@RequestMapping("/app")
public class AppUsersController extends BaseController {

   private static Logger logger = LoggerFactory.getLogger(AppUsersController.class);


    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IAppUsersAddressService iAppUsersAddressService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private IAppAccountService iAppAccountService;
    @Autowired
    private IAppMessageService iAppMessageService;
    @Autowired
    private IAppSktAreaService iAppSktAreaService;
    @Autowired
    private IAppUsersRealnameService iAppUsersRealnameService;
    @Autowired
    private IAppUsersUpgradeService iAppUsersUpgradeService;
    @Autowired
    private IAppShopApproveService iAppShopApproveService;
    @Autowired
    private IAppShopApplysService iAppShopApplysService;
    @Autowired
    private IAppAgentsApplysService iAppAgentsApplysService;
    @Autowired
    private IAppUsersBankcardsService iAppUsersBankcardsService;
    @Autowired
    private IAppSktLogUsersLoginService iAppSktLogUsersLoginService;
    @Autowired
    private IShoppingService shoppingService;
    @Autowired
    private IUsersService usersService;
    @Autowired
    private IAccountService accountService;

    /**
     * 用户登录
     */
    @RequestMapping("/users/login")
    @ResponseBody

    public AppResult userLogins(@ModelAttribute("loginName") String loginName, @ModelAttribute("loginPwd") String loginPwd, @ModelAttribute("verifyCode") String verifyCode,
                                HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!verifyCode.equals("")) {
            String imageCode = (String) cacheUtil.get("imgCode");
            if (imageCode != null) {
                if (!imageCode.equals(verifyCode)) {
                    return AppResult.ERROR("图形验证码错误", -3);
                }
            }
        }
        Users listUser = null;
        if (loginName != null && loginName != "") {
            listUser = appUserService.findListByLoginName(loginName);
            if (listUser == null) {
                return AppResult.ERROR("此用户不存在", -1);
            }
            String userLoginPwd = loginPwd + String.valueOf(listUser.getLoginSecret());
            String encrypt = MD5Util.encrypt(userLoginPwd);
            if (!listUser.getLoginPwd().equals(encrypt)) {
                return AppResult.ERROR("密码错误", -1);
            }
            if (listUser!=null){
                if (listUser.getUserStatus()==0){
                    return AppResult.ERROR("该账户已锁定",-1);
                }
            }
            String token = TokenGenerate.GetGUID();
            cacheUtil.set("token",token);
            System.out.println(token);
            map.put("userId", listUser.getUserId());
            map.put("token", token);
            map.put("isAgent", listUser.getIsAgent());
            map.put("isShop", listUser.getIsShop());
            map.put("isStore", listUser.getIsStore());
            map.put("trueName", listUser.getTrueName());
            map.put("userType", listUser.getUserType());
            map.put("hasPayPwd", MSGUtil.isBlank(listUser.getPayPwd()) ? 0 : 1);
            map.put("userPhone", listUser.getUserPhone());
            map.put("userPhoto",listUser.getUserPhoto());
            map.put("loginName",listUser.getLoginName());
            SktLogUsersLogins sktLogUsersLogins = new SktLogUsersLogins();
            sktLogUsersLogins.setUserId(listUser.getUserId());
            sktLogUsersLogins.setLoginTime(new Date());
            sktLogUsersLogins.setLoginIp(request.getServerName().toString());
            sktLogUsersLogins.setLoginTer(4);
            sktLogUsersLogins.setLoginRemark(token);
            boolean insert = iAppSktLogUsersLoginService.insert(sktLogUsersLogins);
            cacheUtil.set(token, listUser,Long.valueOf(604800));
        }
        return AppResult.OK("登陆成功", map);
    }

    /**
     * 输入密码提交注册
     * 注册2(ZJF)
     *
     * @param loginName
     * @param userPhone
     * @param shareMan
     * @param loginPwd
     * @return
     */
    @RequestMapping("/users/register")
    @ResponseBody
    public AppResult appUserRegister(@ModelAttribute("loginName") String loginName, @ModelAttribute("userPhone") String userPhone, @ModelAttribute("checkData") String checkData, @ModelAttribute("loginPwd") String loginPwd, @ModelAttribute("password_confirm") String password_confirm, @ModelAttribute("regTerminal") Integer regTerminal) {
        if (!loginPwd.equals(password_confirm)) {
            return AppResult.ERROR("两次密码输入不一致", -3);
        }

        Random random = new Random();
        String secret = "";
        for (int i = 0; i < 4; i++) {
            secret += random.nextInt(10);
            if (secret.length() == 1 && secret.equals("0")) {
                secret = random.nextInt(9) + 1 + "";
            }
        }
        Users userByLoginNameOrUserPhone = appUserService.findUserByLoginNameOrUserPhone(loginName);
        Users userByLoginNameOrUserPhone1 = appUserService.findUserByLoginNameOrUserPhone(userPhone);
        if (!MSGUtil.isBlank(userByLoginNameOrUserPhone)||!MSGUtil.isBlank(userByLoginNameOrUserPhone1)){
            return AppResult.ERROR("该账号或手机号已存在",-1);
        }
        Users user = new Users();
        user.setCreateTime(new Date());
        user.setLoginName(loginName);
        user.setLoginSecret(Integer.parseInt(secret));
        user.setLoginPwd(MD5Util.encrypt(loginPwd + secret));
        user.setUserPhone(userPhone);
        if (checkData.equals("")) {
            checkData = null;
        }
        if (checkData != null) {
            Users userInfo = appUserService.findUserByLoginNameOrUserPhone(checkData);
            if (userInfo != null) {
                user.setInviteId(userInfo.getUserId());
            }
        }
        user.setRegTerminal(1);
        user.setIsPrivilege(0);
        user.setIsAgent(0);
        user.setIsShop(0);
        user.setIsStore(0);
        user.setUserType(0);
        user.setRegTerminal(regTerminal);
        boolean userMsg = appUserService.addUserRegister(user);
        if (userMsg) {
            Account account = new Account();
            account.setUserId(user.getUserId());
            account.setCreateTime(new Date());
            boolean accountMsg = iAppAccountService.insert(account);
            if (accountMsg) {
                return AppResult.OK("注册成功", user);
            }
            return AppResult.ERROR("我的账户添加失败", -6);
        }
        if (!userMsg) {
            return AppResult.ERROR("注册失败", -5);
        }
        return AppResult.ERROR("注册失败", -4);
    }

    /**
     * 验证信息(ZJF)，验证分享人或者用户的信息
     */
    @RequestMapping("/users/checkShare")
    @ResponseBody
    public AppResult findShare(@ModelAttribute("checkData") String checkData) {
        boolean responsePhone = MSGUtil.getResponsePhone(checkData);
        Users user = appUserService.findUserByLoginNameOrUserPhone(checkData);
        if(MSGUtil.isBlank(user)){
            return AppResult.ERROR("验证用户信息有误",-1);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", user.getUserId());
        if (responsePhone) {
            map.put("shareInfo",user.getLoginName());
        }else {
            map.put("shareInfo",user.getUserPhone());
        }
        return AppResult.OK("获取成功", map);
    }

    /**
     * 修改登录密码
     *
     * @param userId
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @RequestMapping("/users/modifyPwd")
    @ResponseBody
    public AppResult updateLoginPwd(@ModelAttribute("oldPwd") String oldPwd, @ModelAttribute("loginPwd") String loginPwd, @ModelAttribute("password_confirm") String password_confirm) {
        Map<String, Object> map = new HashMap<String, Object>();
        Users users = (Users) cacheUtil.get(SessionUtils.getSessionId());
        if (users == null || users.equals(null)) {
            return AppResult.ERROR("请先登录", -1);
        }
        Users user = appUserService.selectById(users);
        if(oldPwd == null || "".equals(oldPwd)){
            return AppResult.ERROR("旧密码不能为空", -1);
        }
        if(loginPwd == null || "".equals(loginPwd)){
            return AppResult.ERROR("新密码不能为空", -1);
        }
        String userLoginPwd = oldPwd + String.valueOf(user.getLoginSecret());
        String encrypt = MD5Util.encrypt(userLoginPwd);
        if (!user.getLoginPwd().equals(encrypt)) {
            return AppResult.ERROR("原密码不正确", -1);
        }
        if (!loginPwd.equals(password_confirm)) {
            return AppResult.ERROR("两次输入密码不正确请重新输入", -1);
        }
        String userNewPwd = loginPwd + String.valueOf(user.getLoginSecret());
        user.setLoginPwd(MD5Util.encrypt(userNewPwd));
        boolean usermsg = appUserService.insertOrUpdate(user);
        if (usermsg) {
            return AppResult.OK("修改成功");
        }
        if (!usermsg) {
            return AppResult.ERROR("修改失败", -1);
        }
        return AppResult.ERROR("修改失败", -1);
    }

    /**
     * 修改交易密码
     *
     * @param userId
     * @param newPayPwd
     * @return
     */
    @RequestMapping("/users/modifyPayPwd")
    @ResponseBody
    public AppResult updateUsersPayPwd(@ModelAttribute("payPwd") String payPwd, @ModelAttribute("password_confirm") String password_confirm) {
        Map<String, Object> map = new HashMap<>();
        if (!password_confirm.equals(payPwd)) {
            return AppResult.ERROR("两次密码输入不一致请重新输入", -1);
        }
        Users users = (Users) cacheUtil.get(SessionUtils.getSessionId());
        users.setPayPwd(MD5Util.encrypt(password_confirm+users.getLoginSecret()));
        boolean userMsg = appUserService.updateById(users);
        if (userMsg) {
            String   token=  cacheUtil.get("token").toString();
            cacheUtil.set(token, users,Long.valueOf(604800));
            return AppResult.OK("修改成功", null);
        }
        return AppResult.ERROR("修改错误", -1);
    }

    /**
     * 忘记密码 找回密码
     *
     * @param loginPwd
     * @param password_confirm
     * @param userPhone
     * @return
     */
    @RequestMapping("/users/retrievePwd")
    @ResponseBody
    public AppResult usersRetrievePwd(@ModelAttribute("sendCode") String sendCode, @ModelAttribute("loginPwd") String loginPwd, @ModelAttribute("password_confirm") String password_confirm, @ModelAttribute("userPhone") String userPhone) {
        if (!loginPwd.equals(password_confirm)) {
            return AppResult.ERROR("两次密码输入不一致请重新输入", -1);
        }
        String code1=cacheUtil.get(userPhone).toString();
 //       Integer code1 = Integer.parseInt(cacheUtil.get(userPhone).toString());
//        if (!sendCode.equals(code1)){
//            return AppResult.ERROR("短信验证码输入错误", -1);
//        }
//        if (Integer.parseInt(sendCode) != code1) {
//            return AppResult.ERROR("短信验证码输入错误", -1);
//        }
        Users userByLoginNameOrUserPhone = appUserService.findUserByLoginNameOrUserPhone(userPhone);
        if (MSGUtil.isBlank(userByLoginNameOrUserPhone)){
            return AppResult.ERROR("该手机号未注册",-1);
        }
        cacheUtil.get(userPhone);
        Users user = new Users();
        user.setUserPhone(userPhone);
        user.setLoginPwd(MD5Util.encrypt(loginPwd + userByLoginNameOrUserPhone.getLoginSecret()));
        user.setLoginSecret( userByLoginNameOrUserPhone.getLoginSecret());
        int usermsg = appUserService.updateUsersByUserPhone(user);
        if (usermsg == 1) {
            return AppResult.OK("修改成功", null);
        }
        return AppResult.ERROR("修改失败", -1);
    }

    /**
     * 用户账户查询，我(个人)
     *
     * @param request
     * @return
     */
    @RequestMapping("/users/account")
    @ResponseBody
    public AppResult usersAccount(HttpServletRequest request) {
        try {
            Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
            if(MSGUtil.isBlank(user)){
                return AppResult.ERROR("您未登录", -2);
            }
            UsersAndAccount users_account = appUserService.selectUserAccountDataById(user);
            Map<String, Object> map = new HashMap<>();
            map.put("dataId", user.getUserId());
            map.put("dataFlag", 1);
            Shopping shoppingCount = shoppingService.getShoppingCount(map);
            Account account=new Account();
            account.setUserId(user.getUserId());
            EntityWrapper<Account> entityWrapper=new EntityWrapper<Account>(account);
            Account account1 = accountService.selectOne(entityWrapper);
            if (users_account != null) {
                users_account.setShoppingCount(MSGUtil.isBlank(account1.getShoppingMoney())?"0.00":account1.getShoppingMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                //获取张数(预留功能)
                /*users_account.setShoppingPage(MSGUtil.isBlank(shoppingCount.getOrderNo())?"0":shoppingCount.getOrderNo()+"张");*/
                return AppResult.OK("查询成功", users_account);
            }
            return AppResult.ERROR("查询失败", -1);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("您未登录", -2);
        }
    }


    /**
     * 个人资料
     *
     * @return
     */
    @RequestMapping("/users/personalData")
    @ResponseBody
    public AppResult usersPersonalData() {
        try {
            Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> maps = appUserService.selectUsersAndUserRealNameByUserId(user.getUserId());
            AppUserAddressDTO usersAddress = iAppUsersAddressService.selectUserAddressByUserId(user.getUserId());
            if (!MSGUtil.isBlank(usersAddress)) {
                SktAreas sktAreas = iAppSktAreaService.selectSktAreasById(usersAddress.getAreaId());
                SktAreas sktAreas1 = iAppSktAreaService.selectSktAreasById(usersAddress.getCityId());
                SktAreas sktAreas2 = iAppSktAreaService.selectSktAreasById(usersAddress.getProvinceId());
                usersAddress.setAreaName(sktAreas2.getAreaName() + sktAreas1.getAreaName() + sktAreas.getAreaName());
                map.put("address",usersAddress);
           } else {
                map.put("address", new AppUserAddressDTO());
            }
            CommonModel commonModel=new CommonModel();
            String urls = "http://www.izzht.com/home/users/register?phone=" + maps.get("userPhone");
            maps.put("qrCode", urls);
            map.put("user", maps);
            return AppResult.OK("查询成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("查询失败", -1);
        }
    }


    /**
     * 我的二维码
     *
     * @param response
     */
    @RequestMapping("/users/qrcode")
    @ResponseBody
    public AppResult getQrcodeImge(HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        GetQrCodeInfo getQrCodeInfo = new GetQrCodeInfo();
        BufferedImage bufImg = getQrCodeInfo.encoderQRCoder("我的二维码", response);
        try {
            Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
            String userPhone = user.getUserPhone();
            CommonModel model = new CommonModel();
            String urls = "http://rest.izzht.cn/api/app/users/register?" + userPhone + "=";
            /*File file=new File(urls+"/"+userPhone+".jpg");
            if (!file.exists()){
                file.mkdirs();
            }
            ImageIO.write(bufImg,"jpg",file);
            String qrCodeUrl=urls+"/"+userPhone+".jpg";*/
            return appUserService.qrcode(user, urls);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("对不起您还未登录", -2);
        }
    }


    /**
     * 我的消息
     *
     * @param pageIndex
     * @return
     */
    @RequestMapping("/users/message")
    @ResponseBody
    public AppResult usersMessage(@ModelAttribute("pageIndex") String pageIndex) {
        try {
            Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
            PageHelper.startPage(Integer.parseInt(pageIndex), 15);
            Messages messages = new Messages();
            messages.setReceiveUserId(user.getUserId());
            List<MessagesList> userMessage = iAppMessageService.getMessage(messages);
            return AppResult.OK("查询成功", userMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("查询失败", -2);
        }
    }

    /**
     * 我的消息(详情)
     *
     * @param id
     * @return
     */
    @RequestMapping("/users/messageDetails")
    @ResponseBody
    public AppResult messageDetails(@ModelAttribute("id") String id) {
        Messages messages = iAppMessageService.selectById(Integer.parseInt(id));
        Map<String, Object> map = new HashMap<>();
        map.put("msgContent", messages.getMsgContent());
        return AppResult.OK("查询成功", map);
    }

    /**
     * 删除消息
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/users/messageDel")
    @ResponseBody
    public AppResult messageDel(@ModelAttribute("id") String id, HttpServletRequest
            request) {
        boolean result = iAppMessageService.deleteById(Integer.parseInt(id));
        if (!result) {
            return AppResult.ERROR("删除失败", -1);
        }
        Map<Object, Object> map = new HashMap<>();
        map.put("data", new ArrayList<>());
        return AppResult.OK("删除成功", map);

    }

    /**
     * 验证注册验证基本信息注册1(ZJF)
     *
     * @return
     */
    @RequestMapping("/users/checkRegInfo")
    @ResponseBody
    public AppResult checkRegInfo(@ModelAttribute("loginName") String loginName, @ModelAttribute("userPhone") String userPhone, @ModelAttribute("code") String code, @ModelAttribute("checkData") String checkData, @ModelAttribute("function") String function) {
        boolean responsePhone = MSGUtil.getResponsePhone(loginName);
        if (responsePhone) {
            AppResult.ERROR("用户名不能为手机号码", -1);
        }
        Users userByLoginName = appUserService.findUserByLoginNameOrUserPhone(loginName);
        if (userByLoginName != null) {
            return AppResult.ERROR("该用户名已注册", -2);
        }
        boolean responsePhones = MSGUtil.getResponsePhone(userPhone);
        if (!responsePhones) {
            return AppResult.ERROR("手机号格式不正确", -3);
        }
        Users userByPhone = appUserService.findUserByLoginNameOrUserPhone(userPhone);
        if (userByPhone != null) {
            return AppResult.ERROR("该手机号已注册", -4);
        }
        if (!MSGUtil.isBlank(checkData)) {
            Users checkUsers = appUserService.findUserByLoginNameOrUserPhone(checkData);
            if (MSGUtil.isBlank(checkUsers)) {
                return AppResult.ERROR("请输入真实分享人", -5);
            }
        }
        if (loginName.length() < 3 || loginName.length() > 20) {
            return AppResult.ERROR("用户名格式不正确,长度3—20之间", -1);
        }
        Integer code1 = Integer.parseInt(cacheUtil.get(userPhone).toString());
        if (code1 != null) {
            if (Integer.parseInt(code) == code1) {
                return AppResult.OK("短信校验成功");
            }
            return AppResult.ERROR("短信验证码错误", -1);
        }
        return AppResult.ERROR("短信校验失败", -1);

    }

    /**
     * 用户身份
     *
     * @return
     */
    @RequestMapping("/users/identity")
    @ResponseBody
    public AppResult identity() {
        HashMap<String, Object> map = new HashMap<>();
        try {
            Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
            if(MSGUtil.isBlank(user)){
                return AppResult.ERROR("您还未登陆",-2);
            }
            Users users = appUserService.selectUsersByUserId(user.getUserId());
            //用户是否实名认证处理
            if (!MSGUtil.isBlank(users.getTrueName())) {//已实名
                map.put("realname", "已认证");
                map.put("realnameStatus", 1);
                map.put("realnameRemark", "");
            } else {//未实名   `auditStatus` 审核状态 0 申请中 1 审核通过 2 审核不通过',
                UsersRealname usersRealname = iAppUsersRealnameService.selectUsersRealNameByUserId(user.getUserId());
                if (!MSGUtil.isBlank(usersRealname)) {//未实名，实名中
                    map.put("realname", RemarksGenerate.realname(usersRealname.getAuditStatus()));
                    map.put("realnameStatus", usersRealname.getAuditStatus());
                    map.put("realnameRemark", usersRealname.getAuditRemark());
                } else {//未实名，未进行实名
                    map.put("realname", "未认证");
                    map.put("realnameStatus", -100);
                    map.put("realnameRemark", "");
                }
            }
            //用户是否升级 当前属于什么状态
            if (users.getUserType() == 0 || users.getUserType() == 1) {
                UsersUpgrade usersUpgrade = iAppUsersUpgradeService.selectUsersUpgradeByUserId(users.getUserId());
                if (!MSGUtil.isBlank(usersUpgrade)) {//提交申请中
                    map.put("upgrade", RemarksGenerate.upgrade(usersUpgrade.getStatus()));
                    map.put("upgradeStatus", usersUpgrade.getStatus());
                    map.put("upgradeRemarks", usersUpgrade.getOrderRemarks());
                } else {//未提交申请
                    map.put("upgrade", "未提交升级申请");
                    map.put("upgradeStatus", -100);
                    map.put("upgradeRemarks", "");
                }
                map.put("upgradeorderNo", !MSGUtil.isBlank(usersUpgrade) ? usersUpgrade.getOrderNo() : "");
            } else if (users.getUserType() == 2) {
                map.put("upgrade", "你已经是经理");
                map.put("upgradeStatus", 3);
                map.put("upgradeRemarks", "");
            }
            //用户是否联盟商家 shop_approve
            if (users.getIsStore() == 1) {//已是联盟商家
                map.put("approve", "已是联盟商家");
                map.put("approveStatus", 1);
                map.put("approveRemark", "");
            } else {//不是联盟商家
                SktShopApprove sktShopApprove = iAppShopApproveService.selectShopApproveByUserId(users.getUserId());
                if (!MSGUtil.isBlank(sktShopApprove)) { //申请中
                    map.put("approve", RemarksGenerate.approve(sktShopApprove.getShopStatus()));
                    map.put("approveStatus", sktShopApprove.getShopStatus());
                    map.put("approveRemark", sktShopApprove.getStatusDesc());
                } else {
                    map.put("approve", "不是联盟商家,未申请");
                    map.put("approveStatus", -100);
                    map.put("approveRemark", "");
                }
            }
            //用户是否线上商家 shop_applys
            if (users.getIsShop() == 1) {//已是线上商家
                map.put("shop", "已是线上商家");
                map.put("shopStatus", 3);
                map.put("shopRemark", "");
            } else {//不是线上商家
                SktShopApplys sktShopApplys = iAppShopApplysService.selectShopApplysByUserId(users.getUserId());
                if (!MSGUtil.isBlank(sktShopApplys)) {//申请中
                    map.put("shop", RemarksGenerate.shop(sktShopApplys.getApplyStatus()));
                    map.put("shopStatus", sktShopApplys.getApplyStatus());
                    map.put("shopRemark", sktShopApplys.getApplyDesc());
                } else {
                    map.put("shop", "不是线上商家,未申请");
                    map.put("shopStatus", -100);
                    map.put("shopRemark", "");
                }
            }
            //用户是否代理 agents_applys
            if (users.getIsAgent() > 0) {//已是代理
                map.put("agent", "已是代理");
                map.put("agentStatus", 3);
                map.put("agentRemark", "");
            } else {//不是代理
                AgentsApplys agentsApplys = iAppAgentsApplysService.selectAgentsApplysByUserId(users.getUserId());
                if (!MSGUtil.isBlank(agentsApplys)) {
                    map.put("agent", RemarksGenerate.agent(agentsApplys.getStatus()));
                    map.put("agentStatus", agentsApplys.getStatus());
                    map.put("agentRemark", agentsApplys.getCheckRemark());
                } else {
                    map.put("agent", "不是代理,未申请");
                    map.put("agentStatus", -100);
                    map.put("agentRemark", "");
                }
            }
            map.put("users", users);
            return AppResult.OK("获取成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("获取失败", -3);
        }
    }

    /**
     * 个人认证
     *
     * @param userPhone
     * @param accUser
     * @param ID
     * @param accNo
     * @param bankId
     * @param accArea
     * @param provinceId
     * @param cityId
     * @param areaId
     * @param device
     * @param request
     * @return
     */
    @RequestMapping("/users/quickAuthentication")
    @ResponseBody
    @Transactional
    public AppResult quickAuthentication(@ModelAttribute("userPhone") String userPhone, @ModelAttribute("accUser") String accUser, @ModelAttribute("ID") String ID,
                                         @ModelAttribute("accNo") String accNo, @ModelAttribute("bankId") String bankId, @ModelAttribute("accArea") String accArea,
                                         @ModelAttribute("provinceId") String provinceId, @ModelAttribute("cityId") String cityId, @ModelAttribute("areaId") String areaId,
                                         @ModelAttribute("device") String device, HttpServletRequest request) {
        try {
            Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
            if (MSGUtil.isEmpty(userPhone) || MSGUtil.isEmpty(accUser) || MSGUtil.isEmpty(ID) || MSGUtil.isEmpty(accNo) || MSGUtil.isEmpty(bankId) || MSGUtil.isEmpty(accArea) || MSGUtil.isEmpty(provinceId) || MSGUtil.isEmpty(cityId) ||
                    MSGUtil.isEmpty(areaId) || MSGUtil.isEmpty(device)) {
                return AppResult.ERROR("参数不能为空", -1);
            }
            if (userPhone.length() >= 11) {
                if (!StringUtils.checkTel(userPhone)) {
                    return AppResult.ERROR("请填写正确的联系号码", -1);
                }
            }
            //校验身份证填写
            if (!MSGUtil.verify(ID)) {
                return AppResult.ERROR("身份证填写不正确", -1);
            }
            //校验身份证号码是否已注册
            UsersRealname usersRealname1 = iAppUsersRealnameService.selectUsersRealNameByCardId(ID);
            if (!MSGUtil.isBlank(usersRealname1)) {
                return AppResult.ERROR("身份证号码重复，系统已有该号码的用户", -1);
            }
            //简单校验银行卡
            if (!MSGUtil.checkBankCard(accNo)) {
                return AppResult.ERROR("卡号输入错误！", -1);
            }
            UsersRealname usersRealname = iAppUsersRealnameService.selectUsersRealNameByUserId(user.getUserId());
            if (!MSGUtil.isBlank(usersRealname)) {
                if (usersRealname.getAuditStatus() == 0 || usersRealname.getAuditStatus() == 1) {
                    return AppResult.ERROR("认证审核中或已认证！", -1);
                }
            }
            //过滤填写名字中的特殊字符
            accUser = MSGUtil.StringFilter(accUser);
            if (accUser.equals("")) {
                return AppResult.ERROR("请填写正确姓名", -1);
            }
            //银行卡三要素验证
            JSONObject bankInfoTo3 = BankUtils.getBankInfoTo3(accNo, ID, accUser);
            String status = bankInfoTo3.get("status").toString();
            if (!status.equals("01")) {
                return AppResult.ERROR("银行卡信息有误,请填写正确信息", -1);
            }
            //-----------------------------------------------------------------------------------------
            UsersBankcards usersBankcards = new UsersBankcards();
            usersBankcards.setUserId(user.getUserId());//用户ID
            usersBankcards.setPhone(userPhone);//签约卡的手机号
            usersBankcards.setType(1);//银行卡类型 0充值 支付 1赎回卡
            usersBankcards.setProvinceId(Integer.parseInt(provinceId));//省id
            usersBankcards.setAreaId(Integer.parseInt(areaId));//区县id
            usersBankcards.setCityId(Integer.parseInt(cityId));//市id
            usersBankcards.setBankId(Integer.parseInt(bankId));//银行ID(即开户支行ID)
            usersBankcards.setAccArea(accArea);//开户行
            usersBankcards.setAccNo(accNo);//银行卡号
            usersBankcards.setDataFlag(1);//有效标志
            usersBankcards.setCreateTime(new Date());
            boolean insert = iAppUsersBankcardsService.insert(usersBankcards);
            if (!insert) {
                return AppResult.ERROR("银行卡认证失败", -1);
            }
            UsersRealname usersRealnames = new UsersRealname();
            usersRealnames.setUserId(user.getUserId());//用户ID
            usersRealnames.setPhone(userPhone);//签约卡的手机号
            usersRealnames.setTrueName(accUser);//姓名
            usersRealnames.setCardType(1);//证件类型 1二代身份证 2香港 3澳门 4台湾 5新加坡
            usersRealnames.setCardID(ID);//身份证号码
            usersRealnames.setAuditStatus(1);//审核状态 0 申请中 1 审核通过 2 审核不通过
            usersRealnames.setAuditDatetime(new Date());//审核时间
            usersRealnames.setAddDatetime(new Date());//创建时间
            usersRealnames.setOptTerminal(Integer.parseInt(device));
            String ipAddr = IpAddressUtils.getIpAddr(request);
            usersRealnames.setOptIP(ipAddr);
            boolean insert1 = iAppUsersRealnameService.insert(usersRealnames);
            if (!insert1) {
                return AppResult.ERROR("个人信息认证失败", -1);
            }
            Users users = new Users();
            users.setUserId(user.getUserId());
            users.setTrueName(accUser);
            boolean b = appUserService.updateById(users);
            if (!b) {
                return AppResult.ERROR("修改真实姓名错误", -1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("失败", -1);
        }
        return AppResult.OK("认证成功", null);
    }

    /**
     * 个人认证(已提交)
     *
     * @return
     */
    @RequestMapping("/users/getAuthentication")
    @ResponseBody
    public AppResult getAuthentication() {
        try {
            Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
            UsersRealname usersRealname = iAppUsersRealnameService.selectUsersRealNameByUserId(user.getUserId());
            return AppResult.OK("获取成功", usersRealname);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResult.ERROR("获取失败", -1);
        }

    }

    /**
     * 个人认证(人工)
     *
     * @param userPhone
     * @param accUser
     * @param ID
     * @param cardUrl
     * @param cardBackUrl
     * @param handCardUrl
     * @param device
     * @param request
     * @return
     */
    @RequestMapping("/users/artificialIdent")
    @ResponseBody
    @Transactional
    public AppResult artificialIdent(@ModelAttribute("userPhone") String userPhone, @ModelAttribute("accUser") String accUser, @ModelAttribute("ID") String ID,
                                     @ModelAttribute("cardUrl") String cardUrl, @ModelAttribute("cardBackUrl") String cardBackUrl, @ModelAttribute("handCardUrl") String handCardUrl,
                                     @ModelAttribute("device") String device, HttpServletRequest request) {
        try {
            Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
            if (MSGUtil.isEmpty(userPhone) || MSGUtil.isEmpty(accUser) || MSGUtil.isEmpty(ID) || MSGUtil.isEmpty(cardUrl) || MSGUtil.isEmpty(cardBackUrl) || MSGUtil.isEmpty(handCardUrl) || MSGUtil.isEmpty(device)) {
                return AppResult.ERROR("参数不能为空", -1);
            }
            if (userPhone.length() >= 11) {
                if (!StringUtils.checkTel(userPhone)) {
                    return AppResult.ERROR("请填写正确的联系号码", -1);
                }
            }
            //校验身份证填写
            if (!MSGUtil.verify(ID)) {
                return AppResult.ERROR("身份证填写不正确", -1);
            }
            UsersRealname auditStatus = iAppUsersRealnameService.selectUsersRealNameByUserId(user.getUserId());
            //过滤填写名字中的特殊字符
            accUser = MSGUtil.StringFilter(accUser);
            if (accUser.equals("")) {
                return AppResult.ERROR("请填写正确的姓名 ！", -1);
            }
            CommonModel commonModel=new CommonModel();
            UsersRealname usersRealname = new UsersRealname();
            usersRealname.setOptIP(IpAddressUtils.getIpAddr(request));//操作IP
            usersRealname.setOptTerminal(Integer.parseInt(device));//操作终端 1 PC 2 微信 3 IOS 4 安卓
            usersRealname.setAuditStatus(0);//审核状态 0 申请中 1 审核通过 2 审核不通过
            usersRealname.setAddDatetime(new Date());//创建时间
            usersRealname.setUserId(user.getUserId());//用户ID
            usersRealname.setPhone(userPhone);//签约卡的手机号
            usersRealname.setTrueName(accUser);//姓名
            usersRealname.setCardType(1);//证件类型 1二代身份证 2香港 3澳门 4台湾 5新加坡
            usersRealname.setCardID(ID);//身份证号码
            usersRealname.setHandCardUrl(commonModel.getOSS_DOM()+handCardUrl);//手持身份证照片
            usersRealname.setCardUrl(commonModel.getOSS_DOM()+cardUrl);//身份证正面图片
            usersRealname.setCardBackUrl(commonModel.getOSS_DOM()+cardBackUrl);//身份证背面图片
            if (MSGUtil.isBlank(auditStatus)) {
                //插入申请记录
                boolean insert = iAppUsersRealnameService.insert(usersRealname);
                if (insert) {
                    return AppResult.OK("申请成功", null);
                }
            }
            if (auditStatus.getAuditStatus() == 0 || auditStatus.getAuditStatus() == 1) {
                return AppResult.ERROR("认证审核中或已认证！", -1);
            }
            //校验身份证号码是否已注册
            UsersRealname cardVerify = iAppUsersRealnameService.selectUsersRealNameByCardId(ID);
            if (!MSGUtil.isBlank(cardVerify)) {
                return AppResult.ERROR("身份证号码重复，系统已有该号码的用户", -1);
            }
            if (auditStatus.getAuditStatus() == 2) {
                usersRealname.setRealId(auditStatus.getRealId());
                boolean b = iAppUsersRealnameService.updateById(usersRealname);
                if (b) {
                    AppResult.OK("申请成功", null);
                }
            }
            return AppResult.ERROR("失败", -1);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("错误");
        }

    }


    /**
     * 用户退出
     *
     * @return
     */
    @RequestMapping("/user/loginOut")
    @ResponseBody
    public AppResult loginOut() {
        Users users = (Users) cacheUtil.get(SessionUtils.getSessionId());
        if (cacheUtil.isKeyInCache(SessionUtils.getSessionId())) {
            cacheUtil.remove(SessionUtils.getSessionId());
            return AppResult.OK("退出成功", 1);
        } else {
            return AppResult.ERROR("您并未登录", -1);
        }
    }


}